'use strict';
// npm urllib  mkdirp download ko-sleep --registry=https://r.npm.taobao.org
const urllib = require('urllib');
const urlparse = require('url');
const qs = require('querystring');
const path = require('path');
const fs = require('fs');
const mkdirp = require('mkdirp');
const download = require('download');
const sleep = require('ko-sleep');
const dir = path.join(__dirname, 'download');
// const dir = 'I:\qingshanqu\';
async function download_file(title, filepath, url) {
  if (fs.existsSync(filepath)) {
    return;
  }

  while (true) {
    try {
      console.log(`start downloading ${title}`);
      fs.writeFileSync(filepath, await download(url));
      console.log(`finished downloading ${title}`);
      return;
    } catch (err) {
      console.log('download_file', err);
      await sleep(1000);
    }
  }
}

async function request(url) {
  const res = await urllib.request(url, {
    dataType: 'json',
  });
  const data = res.data;
  return data;
}

async function download_list(grade, week) {
  // const url = `https://www.wuhaneduyun.cn/sky/web/202002/sky_420107_${grade}_${week}.json?v=202006200902`;
  const url = `http://sky.wuhaneduyun.cn/sky-ajax?get=areaCode-420107_grade-${grade}_weekId-${week}`;
  try {
    const data = await request(url);

    for (let item of data.list) {
      console.log(item);
      const { name, gradeName, teacherInfo, teacher, subject, areaName, playBack } = item;
      const title = [areaName, gradeName, subject, name, teacherInfo].join('_');

      if (!playBack.tencentclass) {
        console.log('no playBack.tencentclass');
        // console.log(playBack);
        continue;
      }
      const query = qs.parse(urlparse.parse(playBack.tencentclass.backWebUrl).query);
      const dd = await request(`https://sas.qq.com/cgi-bin/db/ke_act_wuhanLive202001?q={ke_act_wuhanLive202001(id:{_eq:${query['id']}}){name,cid,class_id,task{cname,cid,tname,starttime,endtime,subject,grade,area,liveInfo{islive,hls,flv,rtmp,pcCover,h5Cover},replayInfo{vid,poster},videoInfo{vid,origin,useVideo}}}}&bkn=872789105&r=0.6734728093113342&callback&_=1592579642554`)
      let v = dd.result[0].task.replayInfo.vid.replace(/&amp;/g, '&');
      if (v.trim().length == 0) {
        v = dd.result[0].task.videoInfo.vid.replace(/&amp;/g, '&');
      }
      const aa = urlparse.parse(v);

      if (!aa.pathname) {
        console.log(dd.result[0].task, dd.result[0].task.replayInfo.vid, aa);
        continue;
      }

      const filename = title + '.' + path.basename(aa.pathname);
      const p = [gradeName, subject].join('/');
      const filedir = path.join(dir, p);
      mkdirp.sync(filedir);
      const filepath = path.join(filedir, filename).replace(/\s+/g, '');

      await download_file(filename, filepath, v);
      await sleep(3000);
    }
  } catch (err) {
    console.log(err);
    console.log(`download error ${url}`);

    if (err && err.status == 404) {
      return;
    }
    console.log(err.res);
  }
}

(async function() {
  for (let grade = 1; grade <= 12; grade++ ) {
    for (let week = 0; week <= 20; week++) {
        await download_list(grade, week);
        await sleep(1000);
    }
  }
})();
